"use strict";
//引入第三方模块
const request = require('request-promise');

async function getTokenApi(res, appid, secret) {
  let token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
      `&appid=${appid}&secret=${secret}`
  let webData = await getWebData1(token_url)
  console.log("webData1", webData)
  res.json(webData)
}

async function getWebData1(web_url) {
  return new Promise((resolve, reject) => {
    request(web_url).then(html => {
      if (typeof (html) == "string")
        html = JSON.parse(html)
      resolve(html);
    }).catch(err => {
      reject(err);
    })
  })
}

async function getWebData(config) {
  let params = {app_id:'', code:'', sign:'', grant_type:encodeURIComponent('authorization_code')}
  let {app_id,code,sign,grant_type}=params
  config={
    "method": "post",
    // json:true,
    // body:JSON.stringify(params),
    form:params,
    // params:params,
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    // "url": "http://120.133.52.68:4321/msbzwfw/icity/auth2.0/token",
    "url": "http://120.133.52.68:4321/msbzwfw/icity/auth2.0/token"+`?grant_type=${grant_type}&app_id=${app_id}&code=${code}&sign=${sign}`
  }

  // if (typeof config === 'string') config = JSON.parse(config)
  // if (config.params) {
  //   let params = convertJsonParams(config.params)
  //   config.url = config.url + "?" + params
  // }
  console.log("config.url", config.url)
  return new Promise((resolve, reject) => {
    request({...config}).then(html => {
      if (typeof (html) == "string" && !config.responseType)
        html = JSON.parse(html)
      resolve(html); //成功返回数据
    }).catch(err => {
      reject(err);
    })
  })
}

function convertJsonParams(json) {
  return Object.keys(json).map(key => key + '=' + json[key]).join('&')
}

module.exports = {
  getTokenApi,
  getWebData
};
